#include "Common.h"
#include "NetworkManager.h"
#include "HttpClient.h"
#include "HttpGame.h"
#include "Engine.h"
#include "Game.h"
#include "ENet.h"
#include "TcpServer.h"
#include "TcpClient.h"
#include <winsock2.h>


NetworkManager::NetworkManager()
	: mHttpClient(NULL)
	, mTcpServer(NULL)
	, mTcpClient(NULL)
{
}

NetworkManager::~NetworkManager()
{
	SAFE_DELETE(mHttpClient);
	SAFE_DELETE(mTcpServer);
	SAFE_DELETE(mTcpClient);
}

	
bool NetworkManager::Init(int version)
{
	ENet::enet_initialize();

	mHttpClient = new HttpClient(PLATFORM_URL, PLATFORM_PORT, mSessionKey);
	if (!mHttpClient->Init())
		return false;

	return true;
}

void NetworkManager::Update(float elapsedTime)
{
	if (mTcpServer)
		mTcpServer->Update(elapsedTime);

	if (mTcpClient)
		mTcpClient->Update(elapsedTime);

	if (mHttpClient)
		mHttpClient->Update();
}

void NetworkManager::Destroy()
{
	if (mHttpClient)
		mHttpClient->Destory();

	ENet::enet_deinitialize();
}

bool NetworkManager::Request(HttpRequest* request, ResponseCallback callBack, bool autoDelete)
{
	return mHttpClient->PushRequest(request, callBack, autoDelete);
}

bool NetworkManager::CreateGame()
{
	// clean up the server first.
	if (mTcpServer == NULL)
		mTcpServer = new TcpServer();
	mTcpServer->CleanUp();

	// start the server.
	if (!mTcpServer->Listen(DEFAULT_PORT))
		return false;

	Engine::Instance().getGame()->StartGame();
	return true;
}

void NetworkManager::JoinGame(const char* host, int port)
{
	Engine::Instance().getGame()->StartGame();
}

void NetworkManager::ClientToServer(const void* buff, size_t len, int channel)
{
	if (mTcpClient == NULL)
		return;
	mTcpClient->SendBuff(buff, len, channel);
}

void NetworkManager::ServerToClient(const void* buff, size_t len, int channel)
{
}
